#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 时间     : 2020/12/24 16:21
# 作者     : DL (584054432@qq.com)
# 网址     : https://gitee.com/dingliangPython/
# 软件版本 : Python3.7.3
# 功能     ：


import logging
import os
import pickle

from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QMessageBox, QTableWidgetItem
from pyqt5_common import APP_CONFIG_PATH,APP_NAME ,show_message

from s7configUi import Ui_Form


class Config(object):
    """docstring for Config"""

    def __init__(self):
        super(Config, self).__init__()
        self.path = os.path.join(APP_CONFIG_PATH, APP_NAME,'s7config.dat')

    # 存储配置
    def set_config(self, data):
        with open(self.path, 'wb') as f:
            pickle.dump(data, f)
        config = self.get_config()
        if data == config:
            return True

    # 获取配置
    def get_config(self):
        if not os.path.exists(self.path):
            with open(self.path, 'wb') as f:
                pickle.dump({}, f)
            return {}
        with open(self.path, 'rb') as f:
            data = pickle.load(f)
        return data


class Window(QDialog):
    """docstring for Window"""
    rt_value ={}
    def __init__(self):
        super(Window, self).__init__()
        self.log = logging.getLogger("main.S7Config")
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.s7_config = Config()
        self.config = self.s7_config.get_config()
        self.ui.s7_table.setColumnWidth(0, 120)
        self.ui.s7_table.setColumnWidth(1, 110)
        self.load_s7_config()

    def load_s7_config(self):
        if not self.config:
            self.log.warning("没有找到s7配置")
            return
        self.ui.s7_table.setRowCount(0)
        self.ui.s7_table.setRowCount(len(self.config))
        values = self.config.values()
        for i, row in enumerate(values):
            for ii in range(len(row)):
                self.ui.s7_table.setItem(i, ii, QTableWidgetItem(row[ii] or ''))

    # 保存配置
    @pyqtSlot(bool)
    def on_s7_save_clicked(self):
        rows = self.ui.s7_table.rowCount()
        columns = self.ui.s7_table.columnCount()
        config = {}
        [config.update({
                self.ui.s7_table.item(i, 0).text(): [
                        self.ui.s7_table.item(i, ii).text() if self.ui.s7_table.item(i, ii) else ''
                        for ii in range(columns)]
                })
                for i in range(rows)]
        if self.s7_config.set_config(config):
            show_message("保存配置成功")
            self.close()

    # 添加配置
    @pyqtSlot(bool)
    def on_s7_add_clicked(self):
        rows = self.ui.s7_table.rowCount()
        self.ui.s7_table.insertRow(rows)
        self.ui.s7_table.setItem(rows, 0, QTableWidgetItem('TestPLC'))

    # 删除配置
    @pyqtSlot(bool)
    def on_s7_del_clicked(self):
        select_list = [i.row() for i in self.ui.s7_table.selectionModel().selection().indexes()]
        if len(select_list) == 1:
            self.ui.s7_table.removeRow(select_list[0])
        else:
            show_message("请选择一条需要删除的连接数据?")

    # 关闭事件
    def closeEvent(self, event):
        """
        重写closeEvent方法，实现dialog窗体关闭时执行一些代码
        :param event: close()触发的事件
        :return: None
        """
        reply = QMessageBox.question(self, '配置', "确认保存,配置变化重启生效,是否退出?", QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            os._exit(0)
        else:
            self.hide()


if __name__ == '__main__':
    from PyQt5.QtWidgets import QApplication, QDialog
    import sys
    import loadLog, connect_database

    # import localDB

    log = loadLog.Logger(name = 'main')
    config = {'databasepath': './app/config.db', 'type': 'sqlite'}
    conn = connect_database.Connect(**config)
    app = QApplication(sys.argv)
    gui = Window(conn)
    gui.show()
    sys.exit(app.exec_())